//
//  NSString+Category.m
//  Tool
//
//  Created by Mr.Zhang on 2018/8/28.
//  Copyright © 2018年 Starunion. All rights reserved.
//

#import "NSString+Category.h"
#import <YYText/YYText.h>

@implementation NSString (Category)

+ (NSString*)getPreferredLanguage
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    
    return preferredLang;
    
}

+ (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

+ (BOOL) isWechatName:(NSString *)name {
    
    NSString *emailRegex = @"^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:name];
}

+ (BOOL) isBlankString:(NSString *)string
{
    if ([string isKindOfClass:[NSNumber class]]) {
        return NO;
    }
    
    if (string == nil || string == NULL) {
        return YES;
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([string isKindOfClass: [NSNumber class]]) {
        return NO;
    }
    
    if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (CGFloat)sizeWithString:(NSString *)str font:(UIFont *)font width:(CGFloat)width height:(CGFloat)height {
    
    str = [NSString toStr: str];
    
    CGRect tmpRect = [str boundingRectWithSize:CGSizeMake(width == 0 ? MAXFLOAT : width , height == 0 ? MAXFLOAT : height) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    
    return width == 0 ? tmpRect.size.width : tmpRect.size.height;
}

+ (NSString *)toStr:(id)string {
    if (string == nil || string == NULL) {
        return @"";
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return @"";
    }
    
    if ([string isKindOfClass: [NSNumber class]]) {
        return [NSString stringWithFormat: @"%@", string];
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return @"";
    }
    return string;
}

- (NSString *)decimalString{
    NSNumberFormatter *numFormat = [[NSNumberFormatter alloc] init];
    [numFormat setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [NSNumber numberWithDouble:[self doubleValue]];
    return [numFormat stringFromNumber:num];
}

+ (NSString *)getShowDateNoYestodayWithTime:(long long)time{
    /**
     传入时间转NSDate类型
     */
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    /**
     初始化并定义Formatter
     
     :returns: NSDate
     */
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    
    /**
     *  使用Formatter格式化时间（传入时间和当前时间）为NSString
     */
    NSString *timeStr = [dateFormatter stringFromDate:timeDate];
    NSString *nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    /**
     *  判断前四位是不是本年，不是本年直接返回完整时间
     */
    if ([[timeStr substringWithRange:NSMakeRange(0, 4)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]].location == NSNotFound) {
        return returnStr;
    }else{
        /**
         *  判断是不是本天，是本天返回HH:mm,不是返回MM-dd HH:mm
         */
        if ([[timeStr substringWithRange:NSMakeRange(5, 5)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(5, 5)]].location != NSNotFound) {
            return [timeStr substringWithRange:NSMakeRange(11, 5)];
        }else{
            //不是本天，则按照规则进行判断
            NSString * hour=[nowDateStr substringWithRange:NSMakeRange(11,2)];
            NSString * minite=[nowDateStr substringWithRange:NSMakeRange(14,2)];
            //昨天零点时间
            long long nowseconds=[NSDate date].timeIntervalSince1970-hour.longLongValue*60*60-minite.longLongValue*60-(long long)24*3600;
            if(time/1000.0>nowseconds){
                returnStr = @"昨天";
                return returnStr;
            }else{
                commondateFormatter.dateFormat = @"HH:mm";
                NSString *timestr=[commondateFormatter stringFromDate:timeDate];
                return  [NSString stringWithFormat:@"%@ %@",returnStr,timestr];
            }
        }
    }
    
    return returnStr;
}

+ (NSString *)getCBTShowDateNoYestodayWithTime:(long long)time{
    /**
     传入时间转NSDate类型
     */
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    
    /**
     初始化并定义Formatter
     
     :returns: NSDate
     */
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    
    /**
     *  使用Formatter格式化时间（传入时间和当前时间）为NSString
     */
    NSString *timeStr = [dateFormatter stringFromDate:timeDate];
    NSString *nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    /**
     *  判断前四位是不是本年，不是本年直接返回完整时间
     */
    if ([[timeStr substringWithRange:NSMakeRange(0, 4)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]].location == NSNotFound) {
        return returnStr;
    }else{
        /**
         *  判断是不是本天，是本天返回HH:mm,不是返回yyyy-MM-dd HH:mm
         */
        if ([[timeStr substringWithRange:NSMakeRange(5, 5)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(5, 5)]].location != NSNotFound) {
            return [timeStr substringWithRange:NSMakeRange(11, 5)];
        }else{
            //不是本天，则按照规则进行判断
            commondateFormatter.dateFormat = @"yyyy.MM.dd HH:mm";
            NSString *timestr=[commondateFormatter stringFromDate:timeDate];
            return  [NSString stringWithFormat:@"%@",timestr];
        }
    }
    return returnStr;
}

+ (NSString *)getShowDateMonthDayWithTime:(long long)time{
    /**
     传入时间转NSDate类型
     */
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    return returnStr;
}

+ (NSString *)getCBTShowDateYearMonthWithTime:(long long)time
{
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    return returnStr;
}

+ (NSString *)getCBTShowTimeWithTime:(long long)time
{
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"HH:mm:ss";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    return returnStr;
}

+ (NSString *)getShowDateYearMonthWithTime:(long long)time{
    NSDate *timeDate = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *commondateFormatter = [[NSDateFormatter alloc] init];
    commondateFormatter.dateFormat = @"YYYY/MM/dd";
    NSString * returnStr=[commondateFormatter stringFromDate:timeDate];
    return returnStr;
}

+(NSString *)excludeNullString:(NSString *)text
{
    if ([self isBlankString:text]) {
        return @"";
    }else{
        return text;
    }
}
+(NSString *)numberExcludeNullString:(NSString *)text
{
    if ([self isBlankString:text]) {
        return @"0";
    }else{
        return text;
    }
}

+ (NSMutableAttributedString *)textWithString:(NSString *)string textColor:(UIColor *)textColor font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing
{
    if (string) {
//        [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//        string =[string  stringByReplacingOccurrencesOfString:@" " withString:@""];
//        string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
//        string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string];
        attString.yy_font = font;
        attString.yy_color = textColor;
        attString.yy_lineSpacing = lineSpacing;
        attString.yy_lineBreakMode = NSLineBreakByWordWrapping;
        return attString;
    } else {
        return [[NSMutableAttributedString alloc] initWithString:@""];
    }
}

+ (BOOL) validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL) isETHAddress:(NSString *)ethAddress
{
    NSString *emailRegex = @"^0[x|X]{1}[0-9a-fA-F]{40}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:ethAddress];
}

+ (CGFloat)labelHeightWithAttributedString:(NSMutableAttributedString *)string sizeWidth:(CGFloat)width
{
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:options context:nil];
    return rect.size.height;
}

+ (BOOL) deptNumInputShouldNumber:(NSString *)str
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}

- (BOOL) isPhoneNumber{
    return [NSString isInputRightPhoneNum:self];
}
+ (BOOL) isInputRightPhoneNum:(NSString *)text{
    if ([NSString deptNumInputShouldNumber:text] == NO){
        return NO;
    }
    return YES;
}

+(NSString*)changeTelephone:(NSString*)teleStr{
    if (teleStr.length != 11)return teleStr;
    NSString *string=[teleStr stringByReplacingOccurrencesOfString:[teleStr substringWithRange:NSMakeRange(3,4)]withString:@"****"];
    return string;
    
}
+(NSInteger)countWord:(NSString *)str{
    int strlength = 0;
    char* p = (char*)[str cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}

/**
 判断NSString中是否有表情
 */
+ (BOOL)isContainsEmoji:(NSString *)string {
    string = [NSString toStr:string];
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        // surrogate pair
        if (0xd800 <= hs && hs <= 0xdbff) {
            if (substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f) {
                    isEomji = YES;
                }
            }
        } else {
            // non surrogate
            if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                if (!(9312 <= hs && hs <= 9327)) { // 9312代表①   表示①至⑯
                    isEomji = YES;
                }
            } else if (0x2B05 <= hs && hs <= 0x2b07) {
                isEomji = YES;
            } else if (0x2934 <= hs && hs <= 0x2935) {
                isEomji = YES;
            } else if (0x3297 <= hs && hs <= 0x3299) {
                isEomji = YES;
            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                isEomji = YES;
            }
            if (!isEomji && substring.length > 1) {
                const unichar ls = [substring characterAtIndex:1];
                if (ls == 0x20e3) {
                    isEomji = YES;
                }
            }
        }
    }];
    return isEomji;
}

- (BOOL)isEmoji{
    if ([NSString isBlankString:self]) {
        return NO;
    }
    const unichar high = [self characterAtIndex:0];
    
    // Surrogate pair (U+1D000-1F77F)
    if (0xd800 <= high && high <= 0xdbff && self.length >= 2) {
        const unichar low = [self characterAtIndex:1];
        const int codepoint = ((high - 0xd800) * 0x400) + (low - 0xdc00) + 0x10000;
        
        return (0x1d000 <= codepoint && codepoint <= 0x1f77f);
        
        // Not surrogate pair (U+2100-27BF)
    } else {
        return (0x2100 <= high && high <= 0x27bf);
    }
}

/**
 *  判断字符串中是否存在emoji
 * @param string 字符串
 * @return YES(含有表情)
 */
+ (BOOL)hasEmoji:(NSString*)string
{
    string = [NSString toStr:string];
    NSString *pattern = @"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}

/**
 判断是不是九宫格
 @param string  输入的字符
 @return YES(是九宫格拼音键盘)
 */
+(BOOL)isNineKeyBoard:(NSString *)string
{
    string = [NSString toStr:string];
    NSString *other = @"➋➌➍➎➏➐➑➒";
    int len = (int)string.length;
    for(int i=0;i<len;i++)
    {
        if(!([other rangeOfString:string].location != NSNotFound))
            return NO;
    }
    return YES;
}

+ (BOOL)isCorrectUserName:(NSString *)name
{
    NSString *emailRegex = @"^[a-zA-Z0-9_\\u4e00-\\u9fa5]{1,6}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:name];
}

+ (NSString*)removeFloatAllZero:(NSString*)string
{
    NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}

+ (NSString*)decimalDivisionWithNum:(NSString *)num num1:(NSString *)num1 decimals:(NSInteger)decimals {
    
    NSDecimalNumberHandler*roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:decimals raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    NSDecimalNumber *firstNum =  [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",num]];
    NSDecimalNumber *secondNum =  [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@",num1]];
    NSDecimalNumber *total = [firstNum decimalNumberByDividingBy:secondNum withBehavior:roundUp];
    return [NSString stringWithFormat:@"%@",total];
}
@end
